<?php
declare (strict_types = 1);

namespace app\auth\service;

use app\auth\common\util\ApiUtil;
use app\auth\model\UserModel;

class UserService  extends BaseService
{
    public function __construct(UserModel $userModel)
    {
        $this->userModel = $userModel;
    }

    public function model(){
        return $this->userModel;
    }

    public function list(array $where = [] , array $limit = [], array $sort= []){
        $limit = check_limit($limit);
        $sort = check_sort($sort);
        return $this->userModel->where($where)->limit($limit['page'],$limit['pagesize'])->order($sort[0],$sort[1])->select();
    }

    public function select(array $where = [],$field = ['*']){
        return $this->userModel->field($field)->where($where)->select();
    }

    public function count(array $where = []){
        return $this->userModel->where($where)->count();
    }

    public function find(array $where = []){
        return $this->userModel->where($where)->find();
    }

    public function insertGetId(array $data = []){
        return $this->userModel->insertGetId($data);
    }

    public function update(array $where = [],array $data = []){
        return $this->userModel->where($where)->update($data);
    }

    public function userInfo(string $username, string $password){
        $user_info = $this->find(['username'=>$username,'password'=>UserModel::passwordEncode($password)]);
        if(empty($user_info)) ApiUtil::abort('账号或密码错误');
        //更新登陆时间
        $update_data = array();
        $update_data['last_time'] = time();
        $update_data['last_ip'] = request()->ip();
        $update_data['login_times'] = intval($user_info['login_times'])+1;
        !$this->update(['id'=>$user_info['id']], $update_data) && ApiUtil::abort('更新登陆信息失败');
        return $user_info;
    }
}
